package com.css.zfzx.sjcj.common.utils;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Component
@PropertySource(value = "classpath:platform-config.yml")
public class DownloadUtils {
    @Value("${formExcel.localExcel}")
    private String formLocal;

    public void download(String filename) throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        String type = (new MimetypesFileTypeMap()).getContentType(filename);
        response.setHeader("Content-type", type);
        String code = new String(filename.getBytes("utf-8"), "iso-8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + code);
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
      /*  File picFile = new File(formLocal); // 文件夹的文件执行
        if (!picFile.exists()) { // 文件夹不存在 就创建文件夹
            picFile.mkdirs();
        }*/
        String file = formLocal + "/" + filename;
        InputStream inputStream = new FileInputStream(file);
        bis = new BufferedInputStream(inputStream);

        for (int i = bis.read(buff); i != -1; i = bis.read(buff)) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
        }

    }

    public static void exportExcel(Workbook workbook, String fileName, HttpServletResponse response) {
        if (workbook != null) {
            try {
                fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel");
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                workbook.write(response.getOutputStream());
            } catch (IOException var4) {
                var4.printStackTrace();
            }
        }

    }
}
